//
//  UserCollection.m
//  iengage
//
//  Created by Luis Ziliani on 2/9/09.
//  Copyright 2009 Manas. All rights reserved.
//

#import "UserCollection.h"


@implementation NSMutableArray (UserCollection)

- (void) addUser: (User *)user {
	[self addObject:user];
}

- (User *) userAtIndex:(int) position {
	return [self objectAtIndex:position];
}

- (User *) lastUser {
	return [self lastObject];
}

//Delegate function used by NSArray to order the collection of places by distance to the current location
NSInteger compareDistance(id pl1, id pl2, void* currentLocation){
	User* user1 = (User*)pl1;
	User* user2 = (User*)pl2;
	CLLocationDistance dist1 = [user1 lastDistance];
	CLLocationDistance dist2 = [user2 lastDistance];

	NSInteger result;
	if (dist1 < dist2){
		result = NSOrderedAscending;
	}
	else if (dist1 > dist2){
		result = NSOrderedDescending;
	}
	else {
		result = NSOrderedSame;
	}
	return result;	
}

- (void) fillWithDistances: (CLLocation *) reference  {

	for (User *user in self) {
		[user calculateDistanceFrom: reference];
	}
}

- (UserCollection *) sortByLocation: (CLLocation *) reference {
	[self fillWithDistances: reference];
	
	UserCollection *new = [[UserCollection alloc] initWithArray:[self sortedArrayUsingFunction:compareDistance context:reference]];
	[new autorelease];
	return new;
}

- (void) removeUser: (User *) user {
	[self removeObject:user];
}

- (User *) userByLogin:(NSString *) login {
	for (id user in self) {
		if ([[user login] isEqual: login]) {
			return user;
		}
	}
	return nil;
}

@end
